from redis.connection import BlockingConnectionPool
from redis import Redis
from app.Vendor.utilClass import singleton
from app.Vendor.GetConfig import config

@singleton
class RedisHelper():

    def __init__(self):
        self.__conn = Redis(connection_pool=BlockingConnectionPool(
                                host=config.reids_host,
                                port=config.reids_port,
                                password=config.reids_password,
                                db=config.reids_name)
                            )

    def hget(self,name, key):
        """
        get an item
        从hash中获取对应的proxy, 使用前需要调用changeTable()
        :param proxy:
        :return:
        """
        data = self.__conn.hget(name=name, key=key)
        if data:
            return data.decode('utf-8')
        else:
            return None

    def hlen(self,name):
        """
        Return the number of elements in hash ``name``
        :return:
        """
        return self.__conn.hlen(name)

    def hexists(self,name, key):
        return self.__conn.hexists(name, key)

    def hdel(self,name, key):
        """
        Remove the ``key`` from hash ``name``
        :param key:
        :return:
        """
        self.__conn.hdel(name, key)

    def hincrby(self,name, key, value):
        self.__conn.hincrby(name, key, value)

    def getAll(self,name):
        item_dict = self.__conn.hgetall(name)
        return {key.decode('utf8'): value.decode('utf8') for key, value in item_dict.items()}

    def setex(self,name,value,ex):
        """
        字符串保存 设置过期时间
        :param name: 
        :param value: 
        :param ex: 
        :return: 
        """
        return self.__conn.setex(name,ex,value)

    def get(self,name):
        """
        获取字符串
        :param name: 
        :return: 
        """
        value = self.__conn.get(name)
        if value is not None:
            value = str(value, encoding = "utf8")
        return value


if __name__ == '__main__':
    a = RedisHelper()
    print(a.getAll('useful_proxy'))
